package org.darkforest.common.util;


import org.apache.commons.lang3.StringUtils;
import org.darkforest.model.Member;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

/**
 * ClassName: WebUtil
 * Description:
 * author: Justin
 * date: 14-5-12 下午4:47
 */
public class WebUtil {

    private WebUtil() {

    }

    /**
     * get full url like http://www.baidu.com/s
     *
     * @param request request
     * @return full url
     */
    public static String getFullUrl(HttpServletRequest request) {
        return request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() +
                request.getRequestURI();
    }

    /**
     * get cookie set value
     *
     * @param name    name
     * @param cookies cookie
     * @return value
     */
    public static String getCookie(String name, Cookie[] cookies) {
        if (cookies == null) {
            return null;
        }
        for (Cookie c : cookies) {
            if (name != null && name.equals(c.getName())) {
                return c.getValue();
            }
        }
        return null;
    }

    /**
     * 获得Long类型arraylist列表
     *
     * @param request  request
     * @param listName listname
     * @return list, long
     */
    public static List<Long> getLongListParameter(HttpServletRequest request, String listName) {
        String ids = request.getParameter(listName);
        if (StringUtils.isBlank(ids)) {
            return Collections.emptyList();
        }
        String[] list = ids.split(",");
        List<Long> result = new ArrayList<Long>();

        for (String val : list) {
            result.add(Long.valueOf(val));
        }
        return result;
    }

    /**
     * Gets a parameter as a string.
     *
     * @param request The HttpServletRequest object, known as "request" in a JSP
     *                page.
     * @param name    The name of the parameter you want to get
     * @return The value of the parameter or null if the parameter was not found
     * or if the parameter is a zero-length string.
     */
    public static String getParameter(HttpServletRequest request, String name) {
        return getParameter(request, name, false);
    }

    /**
     * Gets a parameter as a string.
     *
     * @param request        The HttpServletRequest object, known as "request" in a JSP
     *                       page.
     * @param name           The name of the parameter you want to get
     * @param emptyStringsOK Return the parameter values even if it is an empty string.
     * @return The value of the parameter or null if the parameter was not
     * found.
     */
    public static String getParameter(HttpServletRequest request, String name, boolean emptyStringsOK) {
        String temp = request.getParameter(name);
        if (temp != null) {
            if ("".equals(temp) && !emptyStringsOK) {
                return null;
            } else {
                return temp;
            }
        } else {
            return null;
        }
    }

    /**
     * Gets a parameter as a string.
     *
     * @param request  The HttpServletRequest object, known as "request" in a JSP
     *                 page.
     * @param name     The name of the parameter you want to get
     * @param defaultV Return the parameter values even if it is an empty string.
     * @return The value of the parameter or null if the parameter was not
     * found.
     */
    public static String getParameter(HttpServletRequest request, String name, String defaultV) {
        String temp = request.getParameter(name);
        if (temp != null) {
            return temp;
        } else {
            return defaultV;
        }
    }

    /**
     * 如果参数为空值或者null，返回默认值
     *
     * @param request  request
     * @param name     name
     * @param defaultV default value
     * @return value
     */
    public static String getParameterNotEmpty(HttpServletRequest request, String name, String defaultV) {
        String temp = request.getParameter(name);
        if (!StringUtils.isBlank(temp)) {
            return temp;
        } else {
            return defaultV;
        }
    }

    /**
     * Returns a list of parameters of the same name
     *
     * @param request an HttpServletRequest object.
     * @return an array of non-null, non-blank strings of the same name. This
     * method will return an empty array if no parameters were found.
     */
    public static String[] getParameters(HttpServletRequest request, String name) {
        if (name == null) {
            return new String[0];
        }
        String[] paramValues = request.getParameterValues(name);
        if (paramValues == null || paramValues.length == 0) {
            return new String[0];
        } else {
            List<String> values = new ArrayList<String>(paramValues.length);
            for (String paramValue : paramValues) {
                if (!StringUtils.isEmpty(paramValue)) {
                    values.add(paramValue);
                }
            }
            return values.toArray(new String[values.size()]);
        }
    }

    /**
     * Returns a list of parameters of the same name
     *
     * @param request an HttpServletRequest object.
     * @return an array of non-null, non-blank strings of the same name. This
     * method will return an empty array if no parameters were found.
     */
    public static List getParametersAsList(HttpServletRequest request, String name) {
        if (name == null) {
            return Collections.emptyList();
        }
        String[] paramValues = request.getParameterValues(name);
        if (paramValues == null || paramValues.length == 0) {
            return Collections.emptyList();
        } else {
            List<String> values = new ArrayList<String>(paramValues.length);
            for (String paramValue : paramValues) {
                if (!StringUtils.isEmpty(paramValue)) {
                    values.add(paramValue);
                }
            }
            return values;
        }
    }

    /**
     * Returns a list of parameters of the same name
     *
     * @param request an HttpServletRequest object.
     * @return an array of non-null, non-blank strings of the same name. This
     * method will return an empty array if no parameters were found.
     */
    @SuppressWarnings("unchecked")
    public static List<Long> getParametersAsLongList(HttpServletRequest request, String name) {
        if (name == null) {
            return Collections.emptyList();
        }
        String[] paramValues = request.getParameterValues(name);
        if (paramValues == null || paramValues.length == 0) {
            return Collections.emptyList();
        } else {
            List<Long> result = new ArrayList<Long>();
            for (String paramValue : paramValues) {
                if (!StringUtils.isEmpty(paramValue)) {
                    result.add(TypeUtil.parseLong(paramValue, 0));
                }
            }
            return result;
        }
    }

    /**
     * Gets a parameter as a boolean.
     *
     * @param request The HttpServletRequest object, known as "request" in a JSP
     *                page.
     * @param name    The name of the parameter you want to get
     * @return True if the value of the parameter was "true", false otherwise.
     */
    public static boolean getBooleanParameter(HttpServletRequest request, String name) {
        return getBooleanParameter(request, name, false);
    }

    /**
     * Gets a parameter as a boolean.
     *
     * @param request The HttpServletRequest object, known as "request" in a JSP
     *                page.
     * @param name    The name of the parameter you want to get
     * @return True if the value of the parameter was "true", false otherwise.
     */
    public static boolean getBooleanParameter(HttpServletRequest request, String name, boolean defaultVal) {
        String temp = request.getParameter(name);
        if ("true".equals(temp) || "on".equals(temp) || "1".equals(temp)) {
            return true;
        } else {
            return !("false".equals(temp) || "off".equals(temp) || "0".equals(temp)) && defaultVal;
        }
    }

    /**
     * Gets a parameter as an int.
     *
     * @param request The HttpServletRequest object, known as "request" in a JSP
     *                page.
     * @param name    The name of the parameter you want to get
     * @return The int value of the parameter specified or the default value if
     * the parameter is not found.
     */
    public static int getIntParameter(HttpServletRequest request, String name, int defaultNum) {
        String temp = request.getParameter(name);
        if (!StringUtils.isEmpty(temp)) {
            int num = defaultNum;
            try {
                num = Integer.parseInt(temp);
            } catch (Exception ignored) {
            }
            return num;
        } else {
            return defaultNum;
        }
    }

    /**
     * Gets a list of int parameters.
     *
     * @param request    The HttpServletRequest object, known as "request" in a JSP
     *                   page.
     * @param name       The name of the parameter you want to get
     * @param defaultNum The default value of a parameter, if the parameter can't be
     *                   converted into an int.
     */
    public static int[] getIntParameters(HttpServletRequest request, String name, int defaultNum) {
        String[] paramValues = request.getParameterValues(name);
        if (paramValues == null || paramValues.length == 0) {
            return new int[0];
        }
        int[] values = new int[paramValues.length];
        for (int i = 0; i < paramValues.length; i++) {
            try {
                values[i] = Integer.parseInt(paramValues[i]);
            } catch (Exception e) {
                values[i] = defaultNum;
            }
        }
        return values;
    }

    /**
     * Gets a parameter as a double.
     *
     * @param request The HttpServletRequest object, known as "request" in a JSP
     *                page.
     * @param name    The name of the parameter you want to get
     * @return The double value of the parameter specified or the default value
     * if the parameter is not found.
     */
    public static double getDoubleParameter(HttpServletRequest request, String name, double defaultNum) {
        String temp = request.getParameter(name);
        if (temp != null && !"".equals(temp)) {
            double num = defaultNum;
            try {
                num = Double.parseDouble(temp);
            } catch (Exception ignored) {
            }
            return num;
        } else {
            return defaultNum;
        }
    }

    /**
     * Gets a parameter as a long.
     *
     * @param request The HttpServletRequest object, known as "request" in a JSP
     *                page.
     * @param name    The name of the parameter you want to get
     * @return The long value of the parameter specified or the default value if
     * the parameter is not found.
     */
    public static Long getLongParameter(HttpServletRequest request, String name) {
        String temp = request.getParameter(name);
        if (temp != null && !"".equals(temp)) {
            Long num = null;
            try {
                num = Long.parseLong(temp);
            } catch (Exception ignored) {
            }
            return num;
        } else {
            return null;
        }
    }

    /**
     * Gets a parameter as a long.
     *
     * @param request The HttpServletRequest object, known as "request" in a JSP
     *                page.
     * @param name    The name of the parameter you want to get
     * @return The long value of the parameter specified or the default value if
     * the parameter is not found.
     */
    public static long getLongParameter(HttpServletRequest request, String name, long defaultNum) {
        String temp = request.getParameter(name);
        if (temp != null && !"".equals(temp)) {
            long num = defaultNum;
            try {
                num = Long.parseLong(temp);
            } catch (Exception ignored) {
            }
            return num;
        } else {
            return defaultNum;
        }
    }

    /**
     * Gets a parameter as a long.
     *
     * @param request The HttpServletRequest object, known as "request" in a JSP
     *                page.
     * @param name    The name of the parameter you want to get
     * @return The long value of the parameter specified or the default value if
     * the parameter is not found.
     */
    public static Date getDateParameter(HttpServletRequest request, String name) throws ParseException {
        String dateStr = request.getParameter(name);
        Date date = null;
        SimpleDateFormat sdf = new SimpleDateFormat(DateUtil.DEFAULT_DATE_PATTERN);
        date = sdf.parse(dateStr);
        return date;
    }

    /**
     * @param request  request
     * @param name     name
     * @param format   format
     * @param defaultV default value
     * @return
     */
    public static Date getDateParameter(HttpServletRequest request, String name, String format, Date defaultV) {
        String dateStr = request.getParameter(name);
        Date date;
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        try {
            date = sdf.parse(dateStr);
        } catch (Exception e) {
            date = defaultV;
        }
        return date;
    }

    /**
     * Gets a parameter as a long.
     *
     * @param request The HttpServletRequest object, known as "request" in a JSP
     *                page.
     * @param name    The name of the parameter you want to get
     * @return The long value of the parameter specified or the default value if
     * the parameter is not found.
     */
    public static Date getDateParameter(HttpServletRequest request, String name, String format) {
        String dateStr = request.getParameter(name);
        Date date;
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        try {
            date = sdf.parse(dateStr);
        } catch (Exception e) {
            return null;
        }
        return date;
    }

    /**
     * Gets a list of long parameters.
     *
     * @param request    The HttpServletRequest object, known as "request" in a JSP
     *                   page.
     * @param name       The name of the parameter you want to get
     * @param defaultNum The default value of a parameter, if the parameter can't be
     *                   converted into a long.
     */
    public static long[] getLongParameters(HttpServletRequest request, String name, long defaultNum) {
        String[] paramValues = request.getParameterValues(name);
        if (paramValues == null || paramValues.length == 0) {
            return new long[0];
        }
        long[] values = new long[paramValues.length];
        for (int i = 0; i < paramValues.length; i++) {
            try {
                values[i] = Long.parseLong(paramValues[i]);
            } catch (Exception e) {
                values[i] = defaultNum;
            }
        }
        return values;
    }

    /**
     * Gets a list of long parameters.
     *
     * @param request The HttpServletRequest object, known as "request" in a JSP
     *                page.
     * @param name    The name of the parameter you want to get
     */
    public static List<Long> getLongParameterList(HttpServletRequest request, String name) {
        String[] paramValues = request.getParameterValues(name);
        List<Long> values = new ArrayList<Long>();
        if (paramValues == null || paramValues.length == 0) {
            return values;
        }
        for (String paramValue : paramValues) {
            try {
                values.add(Long.parseLong(paramValue));
            } catch (Exception ignored) {
            }
        }
        return values;
    }

    /**
     * Gets a parameter as a string.
     *
     * @param request The HttpServletRequest object, known as "request" in a JSP
     *                page.
     * @param name    The name of the parameter you want to get
     * @return The value of the parameter or null if the parameter was not found
     * or if the parameter is a zero-length string.
     */
    public static String getAttribute(HttpServletRequest request, String name) {
        return getAttribute(request, name, false);
    }

    /**
     * Gets a parameter as a string.
     *
     * @param request        The HttpServletRequest object, known as "request" in a JSP
     *                       page.
     * @param name           The name of the parameter you want to get
     * @param emptyStringsOK Return the parameter values even if it is an empty string.
     * @return The value of the parameter or null if the parameter was not
     * found.
     */
    public static String getAttribute(HttpServletRequest request, String name, boolean emptyStringsOK) {
        String temp = (String) request.getAttribute(name);
        if (temp != null) {
            if ("".equals(temp) && !emptyStringsOK) {
                return null;
            } else {
                return temp;
            }
        } else {
            return null;
        }
    }

    /**
     * Gets an attribute as a boolean.
     *
     * @param request The HttpServletRequest object, known as "request" in a JSP
     *                page.
     * @param name    The name of the attribute you want to get
     * @return True if the value of the attribute is "true", false otherwise.
     */
    public static boolean getBooleanAttribute(HttpServletRequest request, String name) {
        String temp = (String) request.getAttribute(name);
        return temp != null && "true".equals(temp);
    }

    /**
     * Gets an attribute as a int.
     *
     * @param request The HttpServletRequest object, known as "request" in a JSP
     *                page.
     * @param name    The name of the attribute you want to get
     * @return The int value of the attribute or the default value if the
     * attribute is not found or is a zero length string.
     */
    public static int getIntAttribute(HttpServletRequest request, String name, int defaultNum) {
        String temp = (String) request.getAttribute(name);
        if (temp != null && !"".equals(temp)) {
            int num = defaultNum;
            try {
                num = Integer.parseInt(temp);
            } catch (Exception ignored) {
            }
            return num;
        } else {
            return defaultNum;
        }
    }

    /**
     * Gets an attribute as a long.
     *
     * @param request The HttpServletRequest object, known as "request" in a JSP
     *                page.
     * @param name    The name of the attribute you want to get
     * @return The long value of the attribute or the default value if the
     * attribute is not found or is a zero length string.
     */
    public static long getLongAttribute(HttpServletRequest request, String name, long defaultNum) {
        String temp = (String) request.getAttribute(name);
        if (temp != null && !"".equals(temp)) {
            long num = defaultNum;
            try {
                num = Long.parseLong(temp);
            } catch (Exception ignored) {
            }
            return num;
        } else {
            return defaultNum;
        }
    }
    
    /**
     * 获取session中的用户ID方法,暂时调试用
     * @author chenchao
     * @return
     */
    @Deprecated
    public static int getSessionMemberId(){
    	return getSessionMember().getMemberId();
    }
    @Deprecated
    public static Member getSessionMember(){
    	HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
    	Member member = (Member)request.getSession().getAttribute("memInfo");
//    	Member member = new Member();
//    	member.setMemberId(1);
//    	member.setMemberName("测试用户");
//    	member.setMemberPoints(9999);
    	return member;
    }
    
    
    
    public static int getSecurityLevel(Member m){
    	int level = 1;
    	if(m == null){
    		return level;
    	}
    	if(m.getMemberPaypwd() != null && !m.getMemberPaypwd().trim().equals("")){
    		level++;
    	}
    	if(m.getMemberEmailBind() != null && m.getMemberEmailBind() == 1){
    		level++;
    	}
    	if(m.getMemberMobileBind() != null && m.getMemberMobileBind() == 1){
    		level++;
    	}
    	return level;
    }
    
    
    
    
}